package com.bootdo.app.common.aop.exception.handler;

import com.bootdo.app.common.aop.exception.BaseException;
import com.bootdo.app.common.msg.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.net.SocketTimeoutException;


/**
  * @auther: Along
  * @description: 全局异常捕捉
  */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BaseException.class)
    public Response BaseExceptionHandler(BaseException baseException){
        logger.error(baseException.getMessage(),baseException);
        return new Response(baseException.getStatus(),false,baseException.getMessage());
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Response HttpMessageNotReadableException(HttpMessageNotReadableException httpMsgException){
        logger.error(httpMsgException.getMessage(),httpMsgException);
        return Response.fail("缺失请求参数");
    }

    /**
     * 拦截 @Validated | @Valid
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response ConstraintViolationExceptionHandler(MethodArgumentNotValidException ex){
        return Response.fail(ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public Response uploadSizeExceededException(MaxUploadSizeExceededException ex){
        logger.error(ex.getMessage(),ex);
        return Response.fail("单文件上传:文件不能超过500MB;多文件上传:单一文件不能超过500MB,文件总量不能超过1GB.");
    }
    @ExceptionHandler(value = NumberFormatException.class)
    public Response NumberFormatExceptionHandler(NumberFormatException e){
        logger.error(e.getMessage(),e);
        return Response.fail("参数错误");
    }

    @ExceptionHandler(value = SocketTimeoutException.class)
    public Response SocketTimeoutExceptionHandler(SocketTimeoutException e){
        logger.error(e.getMessage(),e);
        return Response.fail("服务未响应");
    }

    @ExceptionHandler(value = Exception.class)
    public Response BaseExceptionHandler(Exception ex){
        logger.error(ex.getMessage(),ex);
        return Response.fail("系统异常，请联系管理员");
    }

}
